<?php

namespace App\Http\Controllers\Api\V1\Mes;

use App\Constants\BaseConstant;
use App\Helpers\ResponseHelper;
use App\Http\Controllers\Controller;
use App\Models\Mes\AuthUser;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;

class LoginController extends Controller
{
    /*
     * 登录
     */
    public function login(Request $request)
    {
        try {
            $data = $request->all();
            $validator = Validator::make($data, [
                "account" => "required",
                "password" => "required"
            ], [
                "account.*" => "请填写账号，账号即您的工号",
                "password.*" => "请填写密码"
            ]);
            if ($validator->fails()) {
                throw new \Exception($validator->errors()->first());
            }
            // 判断账号是否开通
            $auth_user = AuthUser::query()->where("code", $data["account"])->first();
            if (!($auth_user && Hash::check($data["password"], $auth_user->password))) {
                throw new \Exception("账号或密码错误");
            }
            // 判断账号是否开通
            if (!($auth_user->status === BaseConstant::ENABLE)) {
                throw new \Exception("账号已禁用");
            }
        } catch (\Exception $e) {
            return ResponseHelper::json($e->getCode() ?: 20001, $e->getMessage());
        }
        return ResponseHelper::json(0, "登录成功");
    }
}
